package main

import (
	"net"
	"log"
	"time"
	"fmt"
	"bytes"
)

func main()  {
	//1.连接服务器
	conn,err := net.Dial("tcp", "127.0.0.1:3000")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("11111111111")

	//4.关闭连接
	defer conn.Close()

	for i:=0; i<5; i++ {
		fmt.Println("22222222222----i:", i)
		//2.发送消息
		str := "hello server\t"
		conn.Write([]byte(str))

		time.Sleep(time.Second * 2)

		//3.读取服务器响应消息

		data,err := readSocketData(conn)
		if err != nil {
			log.Fatal(err)
		}

		fmt.Println(data)

		time.Sleep(time.Second * 3)
	}

}


func readSocketData(conn net.Conn) (string, error)  {

	buffer := bytes.Buffer{}
	bs := [1]byte{}

	for {
		_,err :=conn.Read(bs[:])
		if err != nil {
			fmt.Println("err:", err)
			return "", err
		}
		//fmt.Println("33333333333")
		if bs[0] == '\t' {
			break
		}
		buffer.Write(bs[:])
	}
	return buffer.String(), nil
}

